package com.autoglm.android.core.execution

import android.util.Log
import com.autoglm.android.core.models.TaskExecutionPlan
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.ConcurrentHashMap

/**
 * 任务状态管理器，用于跟踪任务执行状态
 */
class TaskStateManager {
    
    companion object {
        private const val TAG = "TaskStateManager"
    }
    
    // 当前执行任务
    private var currentTaskPlan: TaskExecutionPlan? = null
    
    // 已完成的步骤ID
    private val completedStepIds = mutableSetOf<String>()
    
    // 步骤执行结果
    private val stepResults = ConcurrentHashMap<String, StepResult>()
    
    // 任务开始时间
    private var taskStartTimeMs = 0L
    
    // 任务状态流
    private val _taskState = MutableStateFlow<TaskState>(TaskState.Idle)
    val taskState: StateFlow<TaskState> = _taskState.asStateFlow()
    
    /**
     * 初始化任务
     * 
     * @param plan 要执行的任务计划
     */
    fun initializeTask(plan: TaskExecutionPlan) {
        Log.d(TAG, "Initializing task with ${plan.steps.size} steps")
        currentTaskPlan = plan
        completedStepIds.clear()
        stepResults.clear()
        taskStartTimeMs = System.currentTimeMillis()
        
        _taskState.update { TaskState.Running(plan, 0, plan.steps.size) }
    }
    
    /**
     * 标记步骤已完成
     * 
     * @param stepId 步骤ID
     * @param result 执行结果
     */
    fun markStepCompleted(
        stepId: String,
        result: StepResult = StepResult.Success()
    ) {
        Log.d(TAG, "Marking step $stepId as completed")
        completedStepIds.add(stepId)
        stepResults[stepId] = result
        
        val plan = currentTaskPlan ?: return
        _taskState.update { 
            if (it is TaskState.Running) {
                it.copy(completedSteps = completedStepIds.size)
            } else {
                TaskState.Running(plan, completedStepIds.size, plan.steps.size)
            }
        }
        
        // 检查是否所有步骤已完成
        if (plan.steps.all { completedStepIds.contains(it.id) }) {
            _taskState.update { TaskState.Completed(plan, getTaskExecutionTimeMs()) }
        }
    }
    
    /**
     * 标记步骤失败
     * 
     * @param stepId 步骤ID
     * @param errorMessage 错误信息
     */
    fun markStepFailed(stepId: String, errorMessage: String) {
        Log.e(TAG, "Step $stepId failed: $errorMessage")
        stepResults[stepId] = StepResult.Failure(errorMessage)
        
        val plan = currentTaskPlan ?: return
        _taskState.update { TaskState.Failed(plan, errorMessage, stepId) }
    }
    
    /**
     * 获取任务执行时间(毫秒)
     */
    fun getTaskExecutionTimeMs(): Long {
        return if (taskStartTimeMs > 0) {
            System.currentTimeMillis() - taskStartTimeMs
        } else {
            0
        }
    }
    
    /**
     * 获取所有步骤结果
     */
    fun getStepResults(): Map<String, StepResult> {
        return stepResults.toMap()
    }
    
    /**
     * 清理任务状态
     */
    fun clear() {
        currentTaskPlan = null
        completedStepIds.clear()
        stepResults.clear()
        taskStartTimeMs = 0
        _taskState.update { TaskState.Idle }
    }
}

/**
 * 步骤执行结果
 */
sealed class StepResult {
    /** 成功 */
    data class Success(val data: Map<String, Any> = emptyMap()) : StepResult()
    
    /** 失败 */
    data class Failure(val errorMessage: String) : StepResult()
}

/**
 * 任务状态
 */
sealed class TaskState {
    /** 空闲状态 */
    object Idle : TaskState()
    
    /** 运行中 */
    data class Running(
        val plan: TaskExecutionPlan,
        val completedSteps: Int,
        val totalSteps: Int
    ) : TaskState()
    
    /** 已完成 */
    data class Completed(
        val plan: TaskExecutionPlan,
        val executionTimeMs: Long
    ) : TaskState()
    
    /** 已失败 */
    data class Failed(
        val plan: TaskExecutionPlan,
        val errorMessage: String,
        val failedStepId: String
    ) : TaskState()
} 